package wjwt

import (
	"fmt"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/spf13/viper"
)

var expierTime int = viper.GetInt("jwt.expireTime")

var secretKey []byte = []byte("TOADY I'AM HAPPY")

func GeneratedToken(param map[string]interface{}) (string, error) {

	claims := jwt.MapClaims{
		"userId": param["userId"],
		"exp":    time.Now().Add(time.Duration(expierTime) * time.Hour).Unix(),
	}

	// 创建一个token对象
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// 使用密钥对token进行签名
	tokenString, err := token.SignedString(secretKey)
	if err != nil {
		return "", fmt.Errorf("signed failed")
	}
	return tokenString, nil
}

func Valid(token string) (bool, error) {
	flag, _, err := ValidAndGet(token)
	return flag, err
}

func ValidAndGet(token string) (bool, jwt.MapClaims, error) {

	// 创建一个token对象
	parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		// 确保使用与生成时相同的签名算法
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return secretKey, nil
	})

	if err != nil || !parsedToken.Valid {
		return false, nil, err
	}
	return true, parsedToken.Claims.(jwt.MapClaims), nil
}
